package com.example.content_provider_client;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MonitorSms extends AppCompatActivity {

    private SmsObserver smsObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitor_sms);

        // 需要先申请权限
        subscribeSms();
    }

    // 给短信应用添加监听器，发布-订阅模式，短信uri是订阅主题，当有新的短信是会通知订阅者
    private void subscribeSms() {
        // 创建短信uri，即订阅的主题
        Uri smsUri = Uri.parse("content://sms");
        /**
         * notifyForDescendants, 是否通知派生主题， bool 类型
         * false 精确匹配
         * true 通知派生主题
         *
         * content://AUTHORITIES/table
         * content://AUTHORITIES/table/#
         * content://AUTHORITIES/table/teacher
         * content://AUTHORITIES/table/student
         *
         * 如果主题为：content://AUTHORITIES/table
         * notifyForDescendants 为 true时，会通知上面所有主题，
         * notifyForDescendants 为 false时，只通知content://AUTHORITIES/table
         */

        // 订阅者，观察者，实现一个onChange方法用于通知时的回调
        smsObserver = new SmsObserver(this);
        getContentResolver().registerContentObserver(smsUri, true, smsObserver);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 取消订阅
        getContentResolver().unregisterContentObserver(smsObserver);
    }

    // handle,还没学
    private static class SmsObserver extends ContentObserver {
        private final Context context;

        public SmsObserver(Context context) {
            super(new Handler(Looper.getMainLooper()));
            this.context = context;
        }

        // 当收到短信变化通知时执行的回调函数
        @Override
        @SuppressLint("Range")
        public void onChange(boolean selfChange, @Nullable Uri uri) {
            super.onChange(selfChange);

            /**
             * 收到一条短信会调用3次onChange方法，分别是3条uri
             * "content://sms/raw/123"  123为短息的id，对应数据库中的 _id
             * "content://sms/inbox/123"  123为短息的id，对应数据库中的 _id
             * "content://sms" android7.0以上，短信标记已读时，出发回调
             */

            boolean isRawUri = uri.toString().contains("content://sms/raw");
            // 不是 content://sms/inbox/xxx 则结束
            if (isRawUri) {
                return;
            }

            String[] whereArgs = new String[]{"address", "body", "date"};
            String sortOrder = "date DESC";

            Cursor cursor = context.getContentResolver().query(uri, whereArgs, null, null, sortOrder);

            if (cursor.moveToNext()) {
                String address = cursor.getString(cursor.getColumnIndex("address"));
                String content = cursor.getString(cursor.getColumnIndex("body"));

                Log.d("zhoutao", String.format("收到短信: 发送人：%s，内容：%s", address, content));

            }
            cursor.close();
        }
    }
}